package com.sshiro.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;
	private Object object = new Object();
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		synchronized (object) {
			SpringUtil.applicationContext = applicationContext;
		}
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 根据Bean名称获取实例
	 * 
	 * @param name
	 * @return
	 * @throws BeansException
	 */
	public static Object getBean(String name) throws BeansException {
		return applicationContext.getBean(name);
	}

	/**
	 * 根据Bean名称和类型信息获取实例，自动完成强制类型转换
	 * 
	 * @param name
	 * @param clazz
	 * @return
	 * @throws BeansException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name, Class<T> clazz)
			throws BeansException {
		return (T) applicationContext.getBean(name);
	}

	/**
	 * 根据类型信息和后缀获取实例，自动完成强制类型转换
	 * 
	 * @param clazz
	 * @param suffix
	 *            后缀，可以为空
	 * @return
	 * @throws BeansException
	 */
	public static <T> T getBean(Class<T> clazz, String suffix)
			throws BeansException {
		String name = StringUtils.uncapitalize(clazz.getSimpleName());
		if (StringUtils.isNotEmpty(suffix)
				&& !StringUtils.endsWith(name, suffix)) {
			name += suffix;
		}
		return (T) applicationContext.getBean(name, clazz);
	}

}
